from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from app import db
from app.models import User, Admin
from app.services.wechat_service import WeChatService
from app.utils.response import success_response, error_response
from app.utils.decorators import admin_required
from loguru import logger
import requests

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/wechat/login', methods=['POST'])
def wechat_login():
    """微信小程序登录"""
    try:
        data = request.get_json()
        code = data.get('code')
        
        if not code:
            return error_response('缺少code参数', 400)
        
        # 获取微信用户信息
        wechat_service = WeChatService()
        user_info = wechat_service.get_user_info(code)
        
        if not user_info:
            return error_response('微信登录失败', 400)
        
        # 查找或创建用户
        user = User.query.filter_by(openid=user_info['openid']).first()
        
        if not user:
            # 创建新用户
            user = User(
                openid=user_info['openid'],
                unionid=user_info.get('unionid'),
                nickname=user_info.get('nickname'),
                avatar_url=user_info.get('avatar_url'),
                gender=user_info.get('gender', 0)
            )
            db.session.add(user)
            db.session.commit()
            logger.info(f"新用户注册: {user.openid}")
        
        # 生成JWT token
        access_token = create_access_token(identity=user.id)
        refresh_token = create_refresh_token(identity=user.id)
        
        return success_response({
            'access_token': access_token,
            'refresh_token': refresh_token,
            'user': user.to_dict()
        })
        
    except Exception as e:
        logger.error(f"微信登录失败: {e}")
        return error_response('登录失败', 500)

@auth_bp.route('/wechat-login', methods=['POST'])
def wechat_login_compatible():
    """微信小程序登录（兼容接口）"""
    try:
        data = request.get_json()
        code = data.get('code')
        
        if not code:
            return error_response('缺少code参数', 400)
        
        # 获取微信用户信息
        wechat_service = WeChatService()
        user_info = wechat_service.get_user_info(code)
        
        if not user_info:
            return error_response('微信登录失败', 400)
        
        # 查找或创建用户
        user = User.query.filter_by(openid=user_info['openid']).first()
        
        if not user:
            # 创建新用户
            user = User(
                openid=user_info['openid'],
                unionid=user_info.get('unionid'),
                nickname=user_info.get('nickname'),
                avatar_url=user_info.get('avatar_url'),
                gender=user_info.get('gender', 0)
            )
            db.session.add(user)
            db.session.commit()
            logger.info(f"新用户注册: {user.openid}")
        
        # 生成JWT token
        access_token = create_access_token(identity=user.id)
        refresh_token = create_refresh_token(identity=user.id)
        
        return success_response({
            'token': access_token,  # 兼容小程序使用的字段名
            'access_token': access_token,
            'refresh_token': refresh_token,
            'user': user.to_dict()
        })
        
    except Exception as e:
        logger.error(f"微信登录失败: {e}")
        return error_response('登录失败', 500)

@auth_bp.route('/admin/login', methods=['POST'])
def admin_login():
    """管理员登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return error_response('用户名和密码不能为空', 400)
        
        # 查找管理员
        admin = Admin.query.filter_by(username=username, is_active=True).first()
                
        if not admin or not admin.check_password(password):
            return error_response('用户名或密码错误', 401)
        
        # 更新最后登录时间
        admin.last_login_at = db.func.now()
        db.session.commit()
        
        # 生成JWT token
        access_token = create_access_token(identity=f"admin_{admin.id}")
        refresh_token = create_refresh_token(identity=f"admin_{admin.id}")
        
        return success_response({
            'access_token': access_token,
            'refresh_token': refresh_token,
            'admin': admin.to_dict()
        })
        
    except Exception as e:
        logger.error(f"管理员登录失败: {e}")
        return error_response('登录失败', 500)

@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """刷新token"""
    try:
        current_user_id = get_jwt_identity()
        new_access_token = create_access_token(identity=current_user_id)
        
        return success_response({
            'access_token': new_access_token
        })
        
    except Exception as e:
        logger.error(f"刷新token失败: {e}")
        return error_response('刷新失败', 500)

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户信息"""
    try:
        current_user_id = get_jwt_identity()
        print('--------')
        print(current_user_id)
        # 判断是用户还是管理员
        if str(current_user_id).startswith('admin_'):
            admin_id = int(current_user_id.split('_')[1])
            admin = Admin.query.get(admin_id)
            if not admin:
                return error_response('用户不存在', 404)
            return success_response(admin.to_dict())
        else:
            user = User.query.get(current_user_id)
            if not user:
                return error_response('用户不存在', 404)
            return success_response(user.to_dict())
            
    except Exception as e:
        logger.error(f"获取用户信息失败: {e}")
        return error_response('获取信息失败', 500)

@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """登出"""
    try:
        # JWT是无状态的，客户端删除token即可
        return success_response({'message': '登出成功'})
        
    except Exception as e:
        logger.error(f"登出失败: {e}")
        return error_response('登出失败', 500) 